//
//  WHPDFManager.m
//  WHEasyBizLink
//
//  Created by shengmeng chen on 2024/11/26.
//

#import "WHPDFManager.h"
#import <CoreGraphics/CoreGraphics.h>
#import <PDFKit/PDFKit.h>


@implementation WHPDFManager
  //方法：1
void WQDrawContent(CGContextRef myContext,
                   CFDataRef data,
                   CGRect rect)
{
    CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData(data);
    CGImageRef image = CGImageCreateWithJPEGDataProvider(dataProvider,
                                                         NULL,
                                                         NO,
                                                         kCGRenderingIntentDefault);
    CGContextDrawImage(myContext, rect, image);
      
    CGDataProviderRelease(dataProvider);
    CGImageRelease(image);
}
  
void MyCreatePDFFile (CFDataRef data,
                      CGRect pageRect,
                      const char *filepath,
                      CFStringRef password)
{
    CGContextRef pdfContext;
    CFStringRef path;
    CFURLRef url;
    CFDataRef boxData = NULL;
    CFMutableDictionaryRef myDictionary = NULL;
    CFMutableDictionaryRef pageDictionary = NULL;
      
    path = CFStringCreateWithCString (NULL, filepath,
                                      kCFStringEncodingUTF8);
    url = CFURLCreateWithFileSystemPath (NULL, path,
                                         kCFURLPOSIXPathStyle, 0);
    CFRelease (path);
    myDictionary = CFDictionaryCreateMutable(NULL,
                                             0,
                                             &kCFTypeDictionaryKeyCallBacks,
                                             &kCFTypeDictionaryValueCallBacks);
    CFDictionarySetValue(myDictionary,
                         kCGPDFContextTitle,
                         CFSTR("Photo from iPrivate Album"));
    CFDictionarySetValue(myDictionary,
                         kCGPDFContextCreator,
                         CFSTR("iPrivate Album"));
    if (password) {
        CFDictionarySetValue(myDictionary, kCGPDFContextUserPassword, password);
        CFDictionarySetValue(myDictionary, kCGPDFContextOwnerPassword, password);
    }
  
    pdfContext = CGPDFContextCreateWithURL (url, &pageRect, myDictionary);
    CFRelease(myDictionary);
    CFRelease(url);
    pageDictionary = CFDictionaryCreateMutable(NULL,
                                               0,
                                               &kCFTypeDictionaryKeyCallBacks,
                                               &kCFTypeDictionaryValueCallBacks);
    boxData = CFDataCreate(NULL,(const UInt8 *)&pageRect, sizeof (CGRect));
    CFDictionarySetValue(pageDictionary, kCGPDFContextMediaBox, boxData);
    CGPDFContextBeginPage (pdfContext, pageDictionary);
    WQDrawContent(pdfContext,data,pageRect);
    CGPDFContextEndPage (pdfContext);
      
    CGContextRelease (pdfContext);
    CFRelease(pageDictionary);
    CFRelease(boxData);
}
  
+ (NSString *)pdfDestPath:(NSString *)filename
{
    return [documentsPath stringByAppendingPathComponent:filename];
}
  
+ (void)WQCreatePDFFileWithSrc:(NSData *)imgData
                    toDestFile:(NSString *)destFileName
                  withPassword:(NSString *)pw
{
    NSString *fileFullPath = [self pdfDestPath:destFileName];
    const char *path = [fileFullPath UTF8String];
    CFDataRef data = (__bridge CFDataRef)imgData;
    UIImage *image = [UIImage imageWithData:imgData];
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    CFStringRef password = (__bridge CFStringRef)pw;
      
    MyCreatePDFFile(data,rect, path, password);
}

//方法2
//步骤说明
//初始化 PDF 渲染器： 定义页面大小（例如 A4）。
//绘制 PDF 内容： 遍历图片数组，每张图片生成一页 PDF。
//保存到文件： 输出 PDF 到指定路径。
- (void)convertImagesToPDF:(NSArray<UIImage *> *)images outputFilePath:(NSString *)filePath {
    // 设置 PDF 页面尺寸（A4 尺寸为例）
    CGRect pdfPageBounds = CGRectMake(0, 0, 595.2, 841.8); // A4 尺寸，单位是点
    UIGraphicsPDFRenderer *pdfRenderer = [[UIGraphicsPDFRenderer alloc] initWithBounds:pdfPageBounds];
    
    NSError *error = nil;
    [pdfRenderer writePDFToURL:[NSURL fileURLWithPath:filePath] withActions:^(UIGraphicsPDFRendererContext * _Nonnull context) {
        for (UIImage *image in images) {
            [context beginPage];
            CGSize imageSize = image.size;
            CGFloat aspectRatio = MIN(pdfPageBounds.size.width / imageSize.width, pdfPageBounds.size.height / imageSize.height);
            CGSize scaledSize = CGSizeMake(imageSize.width * aspectRatio, imageSize.height * aspectRatio);
            CGRect imageRect = CGRectMake((pdfPageBounds.size.width - scaledSize.width) / 2,
                                          (pdfPageBounds.size.height - scaledSize.height) / 2,
                                          scaledSize.width, scaledSize.height);
            [image drawInRect:imageRect];
        }
    } error:&error];
    
    if (error) {
        NSLog(@"Failed to create PDF: %@", error.localizedDescription);
    } else {
        NSLog(@"PDF created successfully at %@", filePath);
    }
}

//方法3
- (void)convertImageToPDFManual:(UIImage *)image outputFilePath:(NSString *)filePath {
    CGRect pageBounds = CGRectMake(0, 0, 595.2, 841.8); // A4 页面大小
    CGContextRef pdfContext = CGPDFContextCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:filePath], &pageBounds, NULL);
    
    if (pdfContext) {
        CGContextBeginPage(pdfContext, NULL);
        CGContextDrawImage(pdfContext, CGRectMake(0, 0, pageBounds.size.width, pageBounds.size.height), image.CGImage);
        CGContextEndPage(pdfContext);
        CGPDFContextClose(pdfContext);
        CGContextRelease(pdfContext);
        NSLog(@"PDF created successfully at %@", filePath);
    } else {
        NSLog(@"Failed to create PDF context.");
    }
}

#pragma mark 图片列表转pdf
+ (BOOL)convertImageToPDFWithPDFKit:(NSArray<UIImage *> *)images outputFilePath:(NSString *)filePath {
    PDFDocument *pdfDocument = [[PDFDocument alloc] init];
    for (int i = 0; i<images.count; i++) {
        UIImage *image = images[i];
        PDFPage *page = [[PDFPage alloc] initWithImage:image];
        [pdfDocument insertPage:page atIndex:i];
    }
    return  [pdfDocument writeToURL:[NSURL fileURLWithPath:filePath]];
}

@end
